﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using CUWo.App.Resources;
using CUWo.Common.Entities;
using CUWo.Common;
using CUWo.Common.WebHelper;
using System.Reflection;
using System.Diagnostics;
using CUWo.Common.Entities.WoInterface;
using CUWo.Common.WoInterfaceCommunication;
using CUWo.Common.Entities.WoInterface.HttpJsonResult;
using CUWo.Common.Entities.WoInterface.HttpArgument;

namespace CUWo.App
{
    /// <summary>
    /// 只用于测试接口
    /// </summary>
    public partial class MainPage : PhoneApplicationPage
    {
        public MainPage()
        {
            InitializeComponent();

            this.Test_WoInterface();
        }


        private void Test_WoInterface()
        {
            JsonResultRootJsonCharacterString jsonCharacterString = new JsonResultRootJsonCharacterString();
            JsonResultRootMsgCharacterString jsonMessageRoot = new JsonResultRootMsgCharacterString();
            JsonResultMessage jsonMessage = new JsonResultMessage();
            JsonResultMessageError messageError = new JsonResultMessageError()
            {
                MessageId = "MOL00101E",
                MessageContent = "手机号码已存在。"
            };
            JsonResultMessageWarn messageWarn = new JsonResultMessageWarn();
            JsonResultMessagePrompt messagePrompt = new JsonResultMessagePrompt();


            jsonMessage.MessageErrors = new List<JsonResultMessageError>() { messageError };
            jsonMessage.MessageWarns = new List<JsonResultMessageWarn>() { messageWarn };
            jsonMessage.MessagePrompts = new List<JsonResultMessagePrompt>() { messagePrompt };
            //
            jsonMessageRoot.Message = jsonMessage;
            jsonCharacterString.RootValue = JSONHelper.Serialize<JsonResultRootMsgCharacterString>(jsonMessageRoot);
            string resultString = JSONHelper.Serialize<JsonResultRootJsonCharacterString>(jsonCharacterString);
            LogHelper.LogInfo(resultString);

            //
            //string mobileNumber = "13021090391", mobilePassword = "pwd@123", mobileOtherPasssword = "pwd@abc";
            string mobileNumber = "15668469578", mobilePassword = "pwd@123", mobileOtherPasssword = "pwd@abc";
            string requestUrl = string.Empty;

            {
                requestUrl = new MobileRegister().GetUrl(mobileNumber, mobilePassword);//OK
                requestUrl = new PasswordUpdate().GetUrl(mobileNumber, mobilePassword, mobileOtherPasssword);//OK
                //requestUrl = new PasswordReset().GetUrl(mobileNumber, mobilePassword);//OK
                requestUrl = new CaptchaSend().GetUrl(mobileNumber);//OK,短信特别慢
                string captcha = "956671";
                requestUrl = new CaptchaConfirm().GetUrl(mobileNumber, captcha);                
                //特定的解析方法
                //ParserJsonResult_1(requestUrl);
            }
            //
            {
                requestUrl = new ActiveInfo().GetUrl(mobileNumber);//OK
                string adPosition = "1";
                requestUrl = new AdInfo().GetUrl(mobileNumber, adPosition);//OK
                requestUrl = new BaseInfo().GetUrl();//OK
                requestUrl = new FlashInfo().GetUrl();//OK，闪屏的图片地址不是绝对地址
                requestUrl = new NewestVersionLast().GetUrl();//OK，实际返回结果与Excel文档中的对应不上
                requestUrl = new NewsChannel().GetUrl(mobileNumber);//OK
                string channelId = "2", timeStamp = UnixTimestampConverter.ConvertLocalToTimestamp(DateTime.Now).ToString();
                requestUrl = new NewsChannelCheck().GetUrl(mobileNumber, channelId, timeStamp);//OK
                string newsId = "0";
                int count = 10;
                ArgsNewsContentMode mode = ArgsNewsContentMode.Front;
                requestUrl = new NewsContent().GetUrl(mobileNumber, channelId, newsId, count, mode);//OK,具体内容是一个新闻地址
                requestUrl = new TrackCurrent().GetUrl(mobileNumber);//OK
                requestUrl = new TrackGroup().GetUrl(mobileNumber);//获取流量包推荐信息
                requestUrl = new TrackHistory().GetUrl(mobileNumber, DateTime.Now.AddDays(-40), DateTime.Now);
                requestUrl = new TrackHome().GetUrl(mobileNumber);
                requestUrl = new TrackCurrentByWebSite().GetUrl(mobileNumber);
                requestUrl = new CheckIn().GetUrl(mobileNumber);//OK，签到成功，但总是提示“msgID:MOL01201W,msgTxt:获取最新版本失败。”
                requestUrl = new MobileNumberLocator().GetUrl(mobileNumber);//OK
                requestUrl = new EmailIsOpen().GetUrl(mobileNumber);//OK
                requestUrl = new EmailUnreader().GetUrl(mobileNumber);//OK
                requestUrl = new EmailRegisterUrl().GetUrl(mobileNumber);//OK
                requestUrl = new EmailSignUrl().GetUrl(mobileNumber);//OK

                ParserJsonResult_2(requestUrl);
            }
            //以下接口未测试通过
            {  
                string channel = "xxxxxx", unikey = "xxxxxx", callback = "xxxxxxx";
                //requestUrl = new NetGetNumberByUnikey().GetUrl(channel, callback);//获取到unikey,然后给NetGetNumber方法用
                //requestUrl = new NetGetNumber().GetUrl(unikey, callback);//要使用NetGetNumberByUnikey中获取到的Unikey                
                //requestUrl = new TrackCurrentByWebSite().GetUrl(mobileNumber);
                //requestUrl = new TrackGroupByWebSite().GetUrl(mobileNumber);

                //ParserJsonResult_1(requestUrl);
            }


            //LogHelper.LogInfo(requestUrl, this.GetType(), MethodBase.GetCurrentMethod());

        }

        void ParserJsonResult_2(string requestUrl)
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            WebTaskHelper webTask = new WebTaskHelper(new Uri(requestUrl));
            IAsyncResult ia = webTask.BeginWebTask(delegate(IAsyncResult callBackResult)
            {
                try
                {
                    this.Dispatcher.BeginInvoke(() =>
                    {
                        string result = webTask.EndWebTask(callBackResult);
                        LogHelper.LogInfo("耗时：" + sw.Elapsed.ToString());
                        if (string.IsNullOrWhiteSpace(result))
                        {
                            LogHelper.LogError("Result is empty.");
                            return;
                        }
                        //
                        if (result.StartsWith("exception:"))
                        {
                            LogHelper.LogError(result);
                            return;
                        }
                        LogHelper.LogInfo(result, this.GetType(), MethodBase.GetCurrentMethod());
                        //
                        JsonResultRootJsonCharacterString rootCharacterString = JSONHelper.Deserialize<JsonResultRootJsonCharacterString>(result);
                        if (rootCharacterString != null)
                        {
                            if (requestUrl.Contains("ol006"))
                            {
                                JsonResultMessageNumberLocator item = JSONHelper.Deserialize<JsonResultMessageNumberLocator>(rootCharacterString.RootValue);
                            }
                            else if (requestUrl.Contains("ol007"))
                            {
                                JsonResultMessageActiveInfo activeInfo = JSONHelper.Deserialize<JsonResultMessageActiveInfo>(rootCharacterString.RootValue);
                            }
                            else if (requestUrl.Contains("ol008"))
                            {
                                JsonResultMessageAdInfo adInfo = JSONHelper.Deserialize<JsonResultMessageAdInfo>(rootCharacterString.RootValue);
                            }
                            else if (requestUrl.Contains("ol009"))
                            {
                                JsonResultMessageNewsChannel adInfo = JSONHelper.Deserialize<JsonResultMessageNewsChannel>(rootCharacterString.RootValue);
                            }
                            else if (requestUrl.Contains("ol010"))
                            {
                                JsonResultMessageTrackCurrent adInfo = JSONHelper.Deserialize<JsonResultMessageTrackCurrent>(rootCharacterString.RootValue);
                            }
                            else if (requestUrl.Contains("ol011"))
                            {
                                JsonResultMessageTrackHistory adInfo = JSONHelper.Deserialize<JsonResultMessageTrackHistory>(rootCharacterString.RootValue);
                            }
                            else if (requestUrl.Contains("ol013"))
                            {
                                JsonResultMessageTrackHome item = JSONHelper.Deserialize<JsonResultMessageTrackHome>(rootCharacterString.RootValue);
                            }
                            else if (requestUrl.Contains("ol012"))
                            {
                                JsonResultMessageCheckIn item = JSONHelper.Deserialize<JsonResultMessageCheckIn>(rootCharacterString.RootValue);
                            }
                            else if (requestUrl.Contains("ol014"))
                            {
                                JsonResultMessageBaseInfo item = JSONHelper.Deserialize<JsonResultMessageBaseInfo>(rootCharacterString.RootValue);
                            }
                            else if (requestUrl.Contains("ol015"))
                            {
                                JsonResultMessageNewsContent item = JSONHelper.Deserialize<JsonResultMessageNewsContent>(rootCharacterString.RootValue);
                            }
                            else if (requestUrl.Contains("ol017"))
                            {
                                JsonResultMessageFlashInfo item = JSONHelper.Deserialize<JsonResultMessageFlashInfo>(rootCharacterString.RootValue);
                            }
                            else if (requestUrl.Contains("ol018"))
                            {
                                JsonResultMessageNewsChannelCheck item = JSONHelper.Deserialize<JsonResultMessageNewsChannelCheck>(rootCharacterString.RootValue);
                            }
                            else if (requestUrl.Contains("ol019"))
                            {
                                JsonResultMessageTrackGroup item = JSONHelper.Deserialize<JsonResultMessageTrackGroup>(rootCharacterString.RootValue);
                            }
                            else if (requestUrl.Contains("ol020"))
                            {
                                JsonResultMessageNewestVersionLast item = JSONHelper.Deserialize<JsonResultMessageNewestVersionLast>(rootCharacterString.RootValue);
                            }
                            else if (requestUrl.Contains("ol021"))
                            {
                                JsonResultMessageEmailIsOpen item = JSONHelper.Deserialize<JsonResultMessageEmailIsOpen>(rootCharacterString.RootValue);
                            }
                            else if (requestUrl.Contains("ol024"))
                            {
                                JsonResultMessageEmailUnreader item = JSONHelper.Deserialize<JsonResultMessageEmailUnreader>(rootCharacterString.RootValue);
                            }
                            else if (requestUrl.Contains("ol025"))
                            {
                                JsonResultMessageEmailRegisterUrl item = JSONHelper.Deserialize<JsonResultMessageEmailRegisterUrl>(rootCharacterString.RootValue);
                            }
                            else if (requestUrl.Contains("ol026"))
                            {
                                JsonResultMessageEmailSignUrl item = JSONHelper.Deserialize<JsonResultMessageEmailSignUrl>(rootCharacterString.RootValue);
                            }
                            //else if (requestUrl.Contains("ol030"))
                            //{
                            //    JsonResultMessageNetGetNumberByUnikey item = JSONHelper.Deserialize<JsonResultMessageNetGetNumberByUnikey>(rootCharacterString.RootValue);
                            //}
                            //else if (requestUrl.Contains("ol029"))
                            //{
                            //    JsonResultMessageNetGetNumber item = JSONHelper.Deserialize<JsonResultMessageNetGetNumber>(rootCharacterString.RootValue);
                            //}
                            else
                            {
                                LogHelper.LogError("未处理！");
                            }

                            //LogHelper.LogInfo(rootMessage.ToString());
                            //LogHelper.LogInfo(rootMessage.Message.ToString());
                            //LogHelper.LogInfo(rootMessage.Message.MessageErrors.ToString());
                            //LogHelper.LogInfo(rootMessage.Message.MessagePrompts.ToString());
                            //LogHelper.LogInfo(rootMessage.Message.MessageWarns.ToString());
                        }

                    });
                }
                catch (Exception err)
                {
                    LogHelper.LogError(err.ToString());
                }
            }, webTask);
        }


        /// <summary>
        /// 解析返回的Json字符串
        /// <para>可用于以下接口</para>
        /// <para>MobileRegister,PasswordUpdate,PasswordReset,CaptchaSend,CaptchaConfirm,CheckIn</para>
        /// </summary>
        /// <param name="requestUrl"></param>
        void ParserJsonResult_1(string requestUrl)
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            WebTaskHelper webTask = new WebTaskHelper(new Uri(requestUrl));
            IAsyncResult ia = webTask.BeginWebTask(delegate(IAsyncResult callBackResult)
            {
                try
                {
                    this.Dispatcher.BeginInvoke(() =>
                    {
                        string result = webTask.EndWebTask(callBackResult);
                        LogHelper.LogInfo("耗时：" + sw.Elapsed.ToString());
                        if (string.IsNullOrWhiteSpace(result))
                        {
                            LogHelper.LogError("Result is empty.");
                            return;
                        }
                        //
                        if (result.StartsWith("exception:"))
                        {
                            LogHelper.LogError(result);
                            return;
                        }
                        LogHelper.LogInfo(result, this.GetType(), MethodBase.GetCurrentMethod());
                        //
                        JsonResultRootJsonCharacterString rootCharacterString = JSONHelper.Deserialize<JsonResultRootJsonCharacterString>(result);
                        if (rootCharacterString != null)
                        {
                            JsonResultRootMsgCharacterString rootMessage = JSONHelper.Deserialize<JsonResultRootMsgCharacterString>(rootCharacterString.RootValue);
                            LogHelper.LogInfo(rootMessage.ToString());
                            LogHelper.LogInfo(rootMessage.Message.ToString());
                            LogHelper.LogInfo(rootMessage.Message.MessageErrors.ToString());
                            LogHelper.LogInfo(rootMessage.Message.MessagePrompts.ToString());
                            LogHelper.LogInfo(rootMessage.Message.MessageWarns.ToString());
                        }

                    });
                }
                catch (Exception err)
                {
                    LogHelper.LogError(err.ToString());
                }
            }, webTask);
        }
    }
}
